<?php
// Saves a HTTP URL for a single object, making it persistent
// POST parameters:
//  permURL: a permanent URL from llHTTPServer 
//  signature: to make spoofing harder
//  timestamp: in-world timestamp retrieved with llGetTimestamp()

if ($_REQUEST['permURL'])
{
	require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
	include(ABS_PATH . "misc/functions.php");
	
	// check for valid signature
	// try to calculate the signature
	if (isset($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY']))
	{
			// this is coming from SL, so we have the object key
		$signature = md5($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . $_REQUEST['timestamp'] . ':9876') ;
	
		if ($signature != $_REQUEST['signature'])
		{
			header("HTTP/1.0 503 Service Unavailable");
			die("Signature does not match - hack attempt?");		
		}
							
// store entry on SQLite3 database
		try {
			$db = new PDO(PDO_PREFIX . SQLITE_DB_FILENAME);
		}
	
		catch(PDOException $e)
		{
			header("HTTP/1.0 503 Service Unavailable");
  			printf("Connect failed: %s\n", $e->getMessage());
   			_log(__FILE__ . " - line " . __LINE__ . ": Error connecting to database from SL: " . $e->getMessage());
    		exit();
    	}

		$query = "REPLACE INTO Positions (`UUID`, `Name`, `PermURL`, `Location`, `Position`, `Rotation`, `Velocity`, `OwnerKey`, `OwnerName`, `ObjectType`, `ObjectClass`, `RateEnergy`, `RateMoney`, `RateHappiness`, `LastUpdate`) VALUES ('" .
			$_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . "','" .
			addslashes($_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME']) . "','" .
			$_REQUEST['permURL'] . "','" .
			$_SERVER['HTTP_X_SECONDLIFE_REGION'] . "','" .
			trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_POSITION'], " <>()\t\n\r\0\x0B") . "','" .
			trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_ROTATION'], " <>()\t\n\r\0\x0B") . "','" .
			trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_VELOCITY'], " <>()\t\n\r\0\x0B") . "','" .
			$_SERVER['HTTP_X_SECONDLIFE_OWNER_KEY'] . "','" .
			$_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME'] . "','" .
			$_REQUEST['objecttype'] . "','" .
			$_REQUEST['objectclass'] . "','" .
			$_REQUEST['rateenergy'] . "','" .
			$_REQUEST['ratemoney'] . "','" .
			$_REQUEST['ratehappiness'] . "','" .
			$_REQUEST['timestamp'] . "')";
		
		try {
			$db->exec($query);
		}
		
		catch(PDOException $e) {
			header("HTTP/1.0 503 Service Unavailable");
   			printf("REPLACE query '%s' failed: '%s'\n", $query, $e->getMessage());
   			_log(__FILE__ . " - line " . __LINE__ . ": REPLACE query '" . $query . "' failed: " . $e->getMessage());
    		exit();
		}
		header("HTTP/1.0 200 OK");
		header("Content-type: text/plain; charset=utf-8");
		echo "'" . $_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME'] . "' successfully updated!";
	}
	else
 {
	 header("HTTP/1.0 503 Service Unavailable");
	 echo "Signature not found";
 }
}
else
{
	header("HTTP/1.0 405 Method Not Allowed");
	echo "No PermURL specified";
}
?>
